<template>
  <div class="uploadWrap" :style="`width:${options.width}px;height:${options.height}px;`">
    <!-- 上传组件 -->
    <van-uploader
      ref="uploaderImg"
      v-model="fileList"
      :after-read="afterRead"
      :max-count="1"
      upload-icon="photo-o"
      :accept="'image/*'"
      :deletable="false"
      @click-preview="preview_uploader(true)"
      @close-preview="preview_uploader(false)"
      :preview-options="options.previewOptions"
    />
    <!-- 重新更换头像 -->
    <van-button v-if="is_preview" class="uploadBtn" type="default" @click="chooseFile">更换头像</van-button>

    <!-- 裁剪组件 -->
    <cropper-view ref="cropperView" :fileType="options.fileType" @getFile="getFile" />
  </div>
</template>
<script>
import cropperView from "./cropperView.vue";
export default {
  components: {
    cropperView,
  },
  props: {
    //上传头像配置
    options: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },
  data() {
    return {
      is_preview: false,
      //默认值 用于恢复回显
      fileDefault: [],
      fileList: [],
      fileData: {},
      //文件名字
      imageFileName: "",
      //裁剪
      showCropper: false,
    };
  },
  methods: {
    //文件读取完成后的回调函数
    afterRead(file) {
      //先清空 双向数据绑定 防止未裁剪 就显示图片
      this.fileList = [];
      this.fileDefault = file;
      this.$refs.cropperView.startCropper(file);
    },
    /**
     * 预览图片
     * boo 布尔 true 显示预览  false 关闭预览
     */
    preview_uploader(boo) {
      this.is_preview = boo;
    },
    /**
     * 更换头像
     */
    chooseFile() {
      const vm = this;
      vm.fileList = [];
      vm.$nextTick(() => {
        vm.$refs.uploaderImg.closeImagePreview();
        vm.$refs.uploaderImg.chooseFile();
      });
    },
    /**
     * 裁剪过后的返回图片文件
     */
    getFile(file) {
      // console.log('返回的文件'+file);
       this.$emit('fileData', file)
      this.fileList = [this.fileDefault];
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./style.scss";
</style>
